from utils.RedisUtil import *
import requests
import json

def history(code, start, end):
    """

    :param code:  股票代码
    :param start: 开始日期  20210101
    :param end:    结束日期  20210102
    :return:
    """
    try:
        url = 'http://q.stock.sohu.com/hisHq?code=cn_{}&start={}&end={}'
        rsp = requests.get(url.format(code, start, end), timeout=5)
        if isinstance(rsp.json(), dict):
            # 需要list
            return []
        if 'hq' not in rsp.json()[0]:  # 需要有 hq字段 否则[0]['hq']报错
            return []
        datas = rsp.json()[0]['hq']
        """
        日期,
        今日开盘价,
        今日收盘价,
        涨跌幅度，
        涨跌百分比,
        今日最低价,
        今日最高价，
        今日成交股票手数,
        今日成交金额(单位：万)
        换手率
        """
        return datas
    except:
        return []

codes = ['SZ000158','SH600830','SH688200','SZ300561','SZ300663','SZ000995','SZ000717','SZ000595']

redis = RedisUtil()
#key = "menu_gets_json"
#al = redis.vget(key)
#if al != None:
#    print("read cache")
for code in codes:
    print(code[2:])
    key = "data_" + str(code[2:])
    content = history(code[2:],"20240801","20240925")
    redis.vset(key, json.dumps(content))
"""
            for row in datas:
                #if row[0] != find_day:
                #    continue
                info = {
                    "code": row1["code"],
                    "trade_date": row[0],
                    "open": row[1],
                    "high": row[6],
                    "low": row[5],
                    "close": row[2],
                    "volume": float(row[7])*100,
                    "money": float(row[8])*10000,
                    "pre_close": 0
                }
"""